<template>
  <div class="approval-container">
    <!-- 搜索条件区域 -->
    <div class="search-wrapper">
      <el-form :inline="true" :model="searchForm" ref="searchForm" class="search-form" label-width="85px" style="text-align: left">
        <div>
          <el-row>
            <el-col :span="6">
              <el-form-item label="食材编号" prop="ingredientsCode">
                <el-input v-model="searchForm.ingredientsCode" placeholder="食材编号" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: center;">
              <el-form-item label="食材名称" prop="ingredientsName">
                <el-input v-model="searchForm.ingredientsName" placeholder="食材名称" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: center;">
              <el-form-item label="供应商名称" prop="supplierName">
                <el-select
                v-model="searchForm.supplierId"
                placeholder="请选择供应商"
                style="width: 100%"
                clearable
                filterable
              >
                <el-option
                  v-for="item in supplierList"
                  :key="item.id"
                  :label="item.supplierName"
                  :value="item.id"
                />
              </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: right;">
              <el-form-item label="价格" prop="price">
                <el-input v-model="searchForm.price" placeholder="价格" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div style="margin-top: 10px;">
          <el-row>
            <el-col :span="6">
              <el-form-item label="创建人" prop="createBy">
                <el-input v-model="searchForm.createBy" placeholder="创建人" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: center;">
              <el-form-item label="创建时间" prop="createTime">
                <el-date-picker v-model="searchForm.createTime" type="date" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="text-align: right;">
              <div class="search-actions">
                <el-button style="background-color: #4C6EE2;color: white;" size="small" @click="handleSearch">搜索</el-button>
                <el-button size="small" @click="resetSearch">重置</el-button>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>

    <!-- 审批状态筛选 -->
    <div class="status-filter" style="display: flex;justify-content: space-between;">
      <el-radio-group v-model="radio" style="margin-top: 9px;margin-left: 17px;" @input="inputGroup" >
        <el-radio :label="1">全部</el-radio>
        <el-radio :label="2">停用</el-radio>
        <el-radio :label="3">未停用</el-radio>
        <el-radio :label="4">食材预警</el-radio>
      </el-radio-group>
      <div>
        <!-- <el-button style="background-color: rgb(243, 245, 255);border: 1px solid #4C6EE2;color: #4C6EE2;" size="small" plain @click="daic">待采清单</el-button> -->
              
              <el-button type="primary" size="small" plain icon="el-icon-plus" @click="handleAdd" v-hasPermi="['food:ingredients:add']">新增</el-button>
        <el-button type="success" size="small" plain icon="el-icon-edit" @click="handleBatchEdit" v-hasPermi="['food:ingredients:edit']">修改</el-button>
        <el-button type="info" size="small" plain icon="el-icon-upload2" @click="handleImport">导入</el-button>
        <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出</el-button>
        <el-button type="danger" size="small" plain icon="el-icon-delete-solid" @click="handleBatchDelete" v-hasPermi="['food:ingredients:edit']">删除</el-button>
      </div>
    </div>

    <!-- 审批数据表格 -->
    <div class="table-wrapper">
      <el-table 
        :data="tableData" 
        style="width: 100%" 
        v-loading="loading"
        :header-cell-style="{ background: '#f8f8f9' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column prop="ingredientsCode" label="食材编号"></el-table-column>
        <el-table-column prop="ingredientsName" label="食材名称" align="left"></el-table-column>
        <el-table-column prop="supplierName" label="供应商名称"  align="left"></el-table-column>
        <el-table-column prop="stockNum" label="库存"  align="left"></el-table-column>
        <el-table-column prop="unit" label="单位"  align="left">
          
          <template slot-scope="scope" v-if="scope.row.unit">
            {{ dict.type.foot_ingredient_type.filter(el=>el.value == scope.row.unit)[0].label }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" align="right">
          <template slot-scope="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="early" label="库存预警" align="left">
          <template slot-scope="scope">
            <!-- <el-tag :type="scope.row.early > 10 ? 'success' : 'danger'"> -->
              {{ scope.row.early }}
            <!-- </el-tag> -->
          </template>
        </el-table-column>
        <el-table-column prop="rate" label="食材损耗率%"  align="left"></el-table-column>
        <el-table-column prop="createBy" label="创建人"  align="left"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150" align="left"></el-table-column>
        <el-table-column prop="remark" label="备注"  align="left" show-overflow-tooltip></el-table-column>

        <el-table-column prop="status" label="状态" width="100" align="center">
          <!-- <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              active-color="#4C6EE2"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template> -->
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : (scope.row.status === '1' ? 'danger' : 'blue')">
              {{ scope.row.status === '0' ? '正常' : (scope.row.status === '1' ? '停用' : "审核中") }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)"                              
            style="color: #4C6EE2;"
            v-hasPermi="['food:ingredients:edit']"
            >编辑</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)" style="color: #4C6EE2;" v-hasPermi="['food:ingredients:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <pagination v-show="pagination.total > 0" :total="pagination.total" :page.sync="pagination.pageNum" :limit.sync="pagination.pageSize" @pagination="fetchData" />
      </div>
    </div>

    <!-- 新增/编辑弹框 -->
    <el-dialog
      :ingredientsName="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      style="border-radius: 10px;"
      @close="resetForm"
    >
    <template #title>
    <div class="custom-dialog-title">
      <div style="display: flex;border-bottom: 1px solid rgba(0, 0, 0, 0.05);padding-bottom: 20px;padding-left: 30px;">
        <div style="background-color: #4C6EE2;border-radius: 20px;width: 4px;margin-right: 8px;height: 20px;margin-top: 6.5px;"></div>
        <span class="title-text" style="font-family: Source Han Sans;font-size: 20px;font-weight: 500;line-height: 31px;text-align: center;letter-spacing: normal;color: #3D3D3D;">{{ dialogTitle }}</span>
      </div>
    </div>
  </template>
  
      <el-form
        ref="ingredientForm"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="top"
        style="padding: 30px;padding-top: 0px;"
        size="medium"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="食材名称" prop="ingredientsName">
              <el-input
                v-model="form.ingredientsName"
                placeholder="请输入食材名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="supplierId">
              <el-select
                v-model="form.supplierId"
                placeholder="请选择供应商"
                style="width: 100%"
                clearable
                filterable
              >
                <el-option
                  v-for="item in supplierList"
                  :key="item.id"
                  :label="item.supplierName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库存" prop="stockNum">
              <el-input
                v-model.number="form.stockNum"
                placeholder="请输入库存"
                clearable
                @input="form.stockNum = form.stockNum.toString().replace(/[^\d]/g, '')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select v-model="form.unit" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in dict.type.foot_ingredient_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input
                v-model="form.price"
                placeholder="请输入价格"
                clearable
                @blur="form.price = Number(form.price).toFixed(2)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="食材损耗率%" prop="rate">
              <el-input
                v-model="form.rate"
                placeholder="请输入食材损耗率"
                clearable
                @blur="form.price = Number(form.price).toFixed(2)"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库存预警" prop="early">
              <el-input
                v-model.number="form.early"
                placeholder="请输入库存预警"
                clearable
                @input="form.early = form.early.toString().replace(/[^\d]/g, '')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否停用" prop="early">
              <el-select v-model="form.status" placeholder="请选择" style="width: 100%;">
                <el-option
                  :key="0"
                  label="正常"
                  :value="String(0)">
                </el-option>
                <el-option
                  :key="1"
                  label="停用"
                  :value="String(1)">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="dialogVisible = false" style="background-color: white;color: #4C6EE2;border: 1px solid #4C6EE2;">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" style="background-color: #4C6EE2;color: white;">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
    <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip text-center" slot="tip">
        <span>仅允许导入xls、xlsx格式文件。</span>
        <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
      </div>
    </el-upload>
    <div slot="footer" class="dialog-footer" style="text-align: center;">
      <el-button @click="upload.open = false" style="background-color: white;color: #4C6EE2;border: 1px solid #4C6EE2;">取 消</el-button>
      <el-button type="primary" @click="submitFileForm" style="background-color: #4C6EE2;color: white;">确 定</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>
import { getList, ingredientAdd, ingredientUpdate,deleteIngredient } from '@/api/ingredient'
import { listData} from '@/api/customer/supplier'
import { getToken } from "@/utils/auth"
import nameding from "@/plugins/download.js"

export default {
  name: "ingredient",
  dicts: ['foot_ingredient_type'],
  data() {
    // 自定义校验规则
    const validatePrice = (rule, value, callback) => {
    if (!value && value !== 0) {
      return callback(new Error('请输入价格'));
    }
    
    // 检查是否为数字
    if (isNaN(value)) {
      return callback(new Error('价格必须为数字'));
    }
    
    // 检查是否大于0
    if (Number(value) <= 0) {
      return callback(new Error('价格必须大于0'));
    }
    
        // 检查小数位数
        const decimalCount = value.toString().split('.')[1]?.length || 0;
      if (decimalCount > 2) {
        return callback(new Error('最多保留两位小数'));
      }
    
    callback();
  };
      
    const validateStock = (rule, value, callback) => {
      if (!value && value !== 0) {
        return callback(new Error('请输入库存数量'));
      }
      if (isNaN(value)) {
        return callback(new Error('库存必须为数字'));
      }
      if (value < 0) {
        return callback(new Error('库存不能为负数'));
      }
      callback();
    };
    
    const validateRate = (rule, value, callback) => {
      if (!value && value !== 0) {
        return callback(new Error('请输入损耗率'));
      }
      
      // 检查是否为数字
      if (isNaN(value)) {
        return callback(new Error('损耗率必须为数字'));
      }
      
      // 检查范围
      const numValue = Number(value);
      if (numValue < 0 || numValue > 100) {
        return callback(new Error('损耗率必须在0-100之间'));
      }
      
      // 检查小数位数
      const decimalCount = value.toString().split('.')[1]?.length || 0;
      if (decimalCount > 2) {
        return callback(new Error('最多保留两位小数'));
      }
      
      callback();
    };
    
    const validateEarly = (rule, value, callback) => {
      if (!value && value !== 0) {
        return callback(new Error('请输入预警值'));
      }
      if (isNaN(value)) {
        return callback(new Error('预警值必须为数字'));
      }
      if (value < 0) {
        return callback(new Error('预警值不能为负数'));
      }
      callback();
    };

    return {
      supplierList:[],
      searchForm: {
        ingredientsCode: '',
        ingredientsName: '',
        supplierName: '',
        price: '',
        applyDate: [],
        createDate: []
      },
      radio: 1,
      loading: false,
      tableData: [],
      multipleSelection: [],
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      title:"",
      upload: {
        open: false,
        title: "",
        isUploading: false,
        updateSupport: 0,
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/food/ingredients/importData"
      },
      dialogVisible: false,
      dialogTitle: '新增食材',
      submitting: false,
      form: {
        ingredientsName: '',
        supplierId: null,
        supplierName: '',
        unit: '',
        price: null,
        rate: null,
        stockNum: null,
        early: null,
        status: '0',
        remark: '',
      },
      rules: {
        ingredientsName: [
          { required: true, message: '请输入食材名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
        ],
        supplierId: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        unit: [
          { required: true, message: '请选择单位', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        // price: [
        //   { required: true, validator: validatePrice, trigger: 'blur' }
        // ],
        stockNum: [
          { required: true, validator: validateStock, trigger: 'blur' }
        ],
        rate: [
          { required: true, validator: validateRate, trigger: 'blur' }
        ],
        early: [
          { required: true, validator: validateEarly, trigger: 'blur' }
        ]
      },
    }
  },
  created() {
    this.fetchData()
    this.glsList()
  },
  methods: {
    daic() {
      this.$router.push("/ingredient/collected")
    },
        /** 导出按钮操作 */
        handleExport() {
      this.download('food/ingredients/export', {
        ...this.searchForm
      }, `食材导出${new Date().toISOString().slice(0, 10)}.xlsx`)
    },
    handleImport() {
      this.upload.title = "食材导入"
      this.upload.open = true
    },
    importTemplate() {
      // const link = document.createElement('a');
      // link.href = '/食材导入模板.xlsx';
      // link.download = '食材导入模板.xlsx';
      // document.body.appendChild(link);
      // link.click();
      // document.body.removeChild(link);
            nameding.name("shicai.xlsx",false)

    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getList()
    },
    methods: {
  handleRateInput(value) {
          // value = value
          //   .replace(/[^\d.]/g, '')  // 只保留数字和小数点
          //   .replace(/(\..*)\./g, '$1')  // 防止多个小数点
          //   .replace(/(\.\d{2})\d+/, '$1')  // 限制小数点后最多两位
          //   .replace(/^(\d+)\.(\d{2}).*$/, '$1.$2');  // 确保格式正确
        }
      },
    inputGroup() {
      this.searchForm.params = null
      if (this.radio == 2) {
        this.searchForm.status = 1
      } else if (this.radio == 3) {
        this.searchForm.status = 0
      } else if (this.radio == 4) { 
        this.searchForm.status = null;
        this.searchForm.params = {}
        this.searchForm.params.type = 1
      }else {
        this.searchForm.status = null
      }
      this.fetchData()
    },
    async fetchData() {
      this.loading = true
      try {
        const data = await getList({...this.searchForm,...this.pagination})
        this.tableData = data.rows
        this.pagination.total = data.total
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.pagination.pageNum = 1
      this.fetchData()
    },
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.fetchData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    async handleStatusChange(row) {
      try {
        await ingredientUpdate(row)
        this.$message.success(`已${row.status === '0' ? '启用' : '停用'}食材【${row.ingredientsName}】`)
      } catch (error) {
        row.status = row.status === '0' ? '1' : '0'
        this.$message.error('状态修改失败')
      }
    },
    async handleAdd() {
      this.dialogTitle = '新增食材'
      this.resetForm()
      this.dialogVisible = true
    },
    async glsList() {
      const res = await listData({
        pageNum:1,
        pageSize: 99999999
      });
      this.supplierList = res.rows
    },
    handleEdit(row) {
      this.dialogTitle = '编辑食材'
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
    },
    handleBatchEdit() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条记录')
        return
      }
      if (this.multipleSelection.length > 1) {
        this.$message.warning('暂不支持批量编辑')
        return
      }
      this.handleEdit(this.multipleSelection[0])
    },
    handleDelete(row) {
      this.$confirm(`确定删除食材【${row.ingredientsName}】吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteIngredient(row.ingredientsId)
          this.$message.success('删除成功')
          this.fetchData()
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条记录')
        return
      }
      const names = this.multipleSelection.map(item => item.ingredientsName).join('、')
      this.$confirm(`确定删除选中的${this.multipleSelection.length}条记录吗?【${names}】`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const ids = this.multipleSelection.map(item => item.ingredientsId).join(',')
          await deleteIngredient(ids)
          this.$message.success('批量删除成功')
          this.fetchData()
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },
    resetForm() {
      this.form = {
        ingredientsName: '',
        supplierId: null,
        supplierName: '',
        unit: '',
        price: null,
        rate: null,
        stockNum: null,
        early: null,
        status: '0',
        remark: '',
      }
      this.$nextTick(() => {
        this.$refs.ingredientForm && this.$refs.ingredientForm.clearValidate()
      })
    },
    async handleSubmit() {
      try {
        await this.$refs.ingredientForm.validate()
        this.submitting = true
        
        const supplier = this.supplierList.find(item => item.id === this.form.supplierId)
        if (supplier) {
          this.form.supplierName = supplier.supplierName
        }
        
        // 格式化数据
        this.form.price = Number(this.form.price)
        this.form.stockNum = parseInt(this.form.stockNum)
        this.form.rate = Number(this.form.rate)
        this.form.early = parseInt(this.form.early)
        this.form.createBy = this.$store.state.user.name
        
        if (this.form.ingredientsId) {
          await ingredientUpdate(this.form)
        } else {
          await ingredientAdd(this.form)
        }
        
        this.$message.success(this.dialogTitle + '成功')
        this.dialogVisible = false
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('表单验证失败:', error)
        }
      } finally {
        this.submitting = false
      }
    },
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
}
</script>

<style scoped>
::v-deep .el-dialog__headerbtn .el-dialog__close{
  font-size: 25px;
}
::v-deep .el-dialog{
  border-radius: 15px;
}
::v-deep .el-form--label-top .el-form-item__label{
 padding: 0;
}
.approval-container {
  padding: 20px;
  background: #fff;
}

.search-wrapper {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-direction: column;
}

.search-row {
  display: flex;
  margin-bottom: 15px;
}

.search-row .el-form-item {
  margin-right: 20px;
  margin-bottom: 0;
}

.search-actions {
  margin-left: auto;
  /* padding-right: 10px; */
}
::v-deep .el-dialog__body{
  padding-top: 0;
}

.status-filter {
  margin-bottom: 15px;
}

.table-wrapper {
  margin-top: 20px;
}

.content-cell {
  padding: 5px 0;
}

.content-cell p {
  margin: 5px 0;
  line-height: 1.5;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.el-table::before {
  display: none;
}

.el-table {
  border: none;
}

.el-table /deep/ th {
  border-bottom: 1px solid #ebeef5;
}

.el-table /deep/ td {
  border-bottom: 1px solid #ebeef5;
}

.el-input-number {
  width: 100%;
}

::v-deep .el-radio__input.is-checked .el-radio__inner {
  background-color: #4C6EE2;
  border: 1px solid #4C6EE2;
  color: black;
}

::v-deep .el-radio__input.is-checked + .el-radio__label {
  color: black;
}

::v-deep .el-form-item {
  margin-bottom: 8px;
  margin-right:0;
}

::v-deep .el-input--medium .el-input__inner {
  height: 32px;
  line-height: 32px;
  border-radius: 8px;
  background: rgba(0, 0, 0, 0);
  box-sizing: border-box;
  border: 1px solid rgba(0, 0, 0, 0.2);
}
</style>